//最新的，限制管理员不能建管理员
var mobile = ""; var re_records = 0;
$(function () {

    if (sessionStorage.getItem("isgroup") == "1") {
        $("#add").hide();
    }
    $("#add").click(function (z) {
        $("#user_name").attr("disabled", false);
        $("#myModal").find("span").empty(); $("#myModal").find("input").val("");
        $("#myModalLabel").text("新增");
        mobile = "";
        //2操作员，3审核
        if (sessionStorage.getItem("userId") != "1" && sessionStorage.getItem("roleId") == "1") {
            $("#jiaose option :first").hide();
            $("#jiaose").val("2");
            $("#jiaose").removeAttr("disabled");
            console.log("进来")
        }
        if (sessionStorage.getItem("userId") == "1" && sessionStorage.getItem("roleId") == "1") {
            $("#jiaose").removeAttr("disabled");
        }
        if (sessionStorage.getItem("roleId") == "2") {
            $("#jiaose option :first").hide();
            $("#jiaose").val("2");
        }
        if (sessionStorage.getItem("roleId") == "3") {
            $("#jiaose option :first").hide();
            $("#jiaose").val("3");
        }



    });

    //appvm.prompt();
    // domain.jsonthis.modify();
});


$(document).ready(function () {

    //$.fn.zTree.init($("#treeDemo"), setting, zNodes);
    domain.staticzt = "456";
    domain.ajaxUrl({
        method: 'POST',
        url: domain.testUrl + "/Threeinjection/basicmManagementpage/queryRoleName",
        data: { sessionid: sessionStorage.getItem("sid") },
        // datatype:"JSON",
        success: function (response) {
            $.each(JSON.parse(response).lgvsRole, function (i, item) {

                //console.log(item.roleName);
                var json = "<option value='" + item.roleId + "'>" + item.roleName + "</option>";
                $("#jiaose").append(json);
                if (sessionStorage.getItem("userId") != "1" && sessionStorage.getItem("roleId") == "1") {
                    $("#jiaose option:first").hide();
                    console.log("隐藏了")
                }

            });

            //  that.ret=data.ret;
            //that.options=JSON.parse(lgvsRole).lgvsRole;



        }
    });

});

$(document).ready(function () {
    $.jgrid.defaults.styleUI = "Bootstrap";
    $("#table_list_1").jqGrid({
        data: [],
        datatype: "local",
        height: "100%",
        autowidth: true,
        shrinkToFit: true,
        rowNum: 20,
        rowList: [10, 20, 30, 60, 90, 100, 200, 500],
        //colNames: ["编号", "名称", "手机号码"],
        colModel: [{
            name: 'user_id', index: 'user_id', align: "center", width: 30, label: "编号", align: 'center',


        },


        {
            name: 'user_name', index: 'user_name', align: "center", width: 30, label: "名称", align: 'center',


        },
        {
            name: 'coName', index: 'coName', align: "center", width: 30, label: "单位名称", align: 'center',
        },
        {
            name: 'roleName', index: 'roleName', align: "center", width: 30, label: "角色职能", align: 'center',
        },
        {
            name: 'mobile', index: 'mobile', align: "center", width: 30, label: "手机号码", align: 'center',


        },
        {
            name: 'Start_time', index: 'Start_time', align: "center", width: 30, label: "时间", align: 'center',
            formatter: function (value, options, row) {

                if (typeof (value) != "undefined") {
                    try {
                        var date = new Date(value)

                        return date.Format("yyyy-MM-dd hh:mm:ss");
                    } catch (ex) {

                        console.log(ex);
                    }
                }
                return "";
            }

        },
        {
            name: '', index: '', width: 25, align: "center", label: "操作", align: 'center',
            formatter: function (value, options, row) {

                //console.log(options.rowId);
                var html = "<button type='button'  class='btn btn-primary' onclick=modify('" + options.rowId + "');>修改</button>";

                return html;
            }

        },


        ],
        pager: "#pager_list_1",
        viewrecords: true,
        multiselect: true,
        caption: "用户列表",
        hidegrid: false,
        ondblClickRow: function (row) {


            $("#update").click();
            modify(row);
            // $('#myModal').modal('show')

        },
        onPaging: function (pageBtn) {
            console.log(":" + pageBtn);
            //	    	var re_records = $jqgrid.getGridParam('records');//获取返回的记录数
            var re_page = $("#table_list_1").getGridParam('page');//获取返回的当前页
            var re_rowNum = $("#table_list_1").getGridParam('rowNum');//获取每页数
            var re_total = $("#table_list_1").getGridParam('lastpage');//获取总页数
            //alert(re_total);

            if (pageBtn === "next") {
                // initJqgrid(re_page+1,re_rowNum);
                // if()
                pageval = pageval + 1;
                cxlist();
            }
            if (pageBtn === "prev") {

                pageval = pageval - 1; cxlist();
            }

            if (pageBtn == "last") {

                pageval = re_total;

                cxlist();

            }
            if (pageBtn == "first") {

                pageval = 1;

                cxlist();

            }

            if (pageBtn == "records") {

                sizeval = $(".ui-pg-selbox").val();
                pageval = 1;
                cxlist();
            }
        },

    });
    $("#table_list_1").setGridHeight($(window).height() * 0.73);

    $(window).resize(function () {
        $("#table_list_1").setGridWidth($(window).width());
        $("#table_list_1").setGridHeight($(window).height() * 0.73);

    });
});
var sizeval = 20;
var pageval = 1;
var usernameval = $("#usnameval").val();
var conameval = "";
var json = "";
window.cxlist = function () {

    domain.ajaxUrl({
        method: 'POST',
        url: domain.testUrl + "/Threeinjection/basicmManagementpage/userManagementpage",
        data: { size: sizeval, page: pageval, username: $("#usnameval").val(), coid: this.sessionStorage.getItem("coid"), sessionid: sessionStorage.getItem("sid") },
        // datatype:"JSON",
        success: function (response) {
            json = response;
            var data = JSON.parse(response);
            var reader = {
                root: function (obj) { return data.rows; },
                page: function (obj) { return pageval; },
                total: function (obj) { return data.taotal; },
                records: function (obj) {

                    return data.records;
                },

            };

            $("#table_list_1").setGridParam({ data: data.rows, localReader: reader }).trigger('reloadGrid');

            re_records = $("#table_list_1").getGridParam('records');

            if (re_records == 0 || re_records == null) {

                if ($(".norecords").html() == null) {
                    $("#usnameval").val("");
                    $("#table_list_1").parent().append("<div class=\"norecords\">没有符合数据</div>");
                }
                $(".norecords").show();
            } else {

                $(".norecords").hide();
            }



            // console.log(response);

        }
    });
}
$(function () {
    $("button").eq(0).click(function () {
        sizeval = 20;
        pageval = 1;
        $(".ui-pg-selbox").val(20);
        $("#table_list_1").setGridParam({ rowNum: 20 });
        cxlist();
    });
    cxlist();
    $("#citySel").click(function () {
        var cityObj = $("#citySel");
        var cityOffset = $("#citySel").offset();
        $("#menuContent").css({ left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px" }).slideDown("fast");
        $("body").bind("mousedown", onBodyDown);
    });
    $("#company_name").click(function () {
        var cityObj = $("#company_name");
        var cityOffset = $("#company_name").offset();
        $("#menuContenttow").css({ left: cityOffset.left + "px", top: cityOffset.top + cityObj.outerHeight() + "px" }).slideDown("fast");

        $("body").bind("mousedown", onBodyDowntow);
    });

    $("#user_name").blur(function () {
        $("#myModal").find("span").eq(1).text("");
        if ($("#user_name").val().length == 0) {
            $("#myModal").find("span").eq(0).text("用户名不能为空");
            //  $("#user_name").focus();
            return;
        }
        if ($("#user_name").val().length > 12) {
            $("#myModal").find("span").eq(0).text("用户名的长度不超过12");
            //  $("#user_name").focus();
            return;
        }
        // if($("#user_name").val().length>0 && $("#user_name").val().length<6){
        //  $("#myModal").find("span").eq(0).text("长度只能在6-20个字符之间");
        //  $("#user_name").focus();  
        //  return;
        // }



        if ($("#myModalLabel").text() == "新增") {
            domain.ajaxUrl({
                method: 'POST',
                url: domain.testUrl + "/Threeinjection/user/queryByUserName",
                data: { "userName": $("#user_name").val() },
                success: function (response) {

                    if (response == "\"no\"") {

                        $("#myModal").find("span").eq(0).text("用户名已经存在");
                        // $("#user_name").focus();
                        return;
                    }
                }

            });
        }
    });


    $("#mobile").blur(function () {
        $("#myModal").find("span").eq(1).text("");
        if ($("#mobile").val().length == 0) {

            $("#myModal").find("span").eq(1).text("手机号码不能为空");
            // $("#mobile").focus();
            return;
        }

        if (!(/^1(?:3\d|4[4-9]|5[0-35-9]|6[67]|7[0135678]|8\d|9\d)\d{8}$/.test($("#mobile").val()))) {
            $("#myModal").find("span").eq(1).text("手机号码输入错误");
            // $("#mobile").focus();
            return;
        }

        // if($("#mobile").val().substr(0,3)!=138&&$("#mobile").val().substr(0,3)!=189&&$("#mobile").val().substr(0,3)!=139&&$("#mobile").val().substr(0,3)!=158&&$("#mobile").val().substr(0,3)!=188&&$("#mobile").val().substr(0,3)!=157||$("#mobile").val().length!=11){

        //  $("#myModal").find("span").eq(1).text("手机号格式不正确");
        //$("#mobile").focus();
        // return;
        // }
        if (mobile != $("#mobile").val()) {
            domain.ajaxUrl({
                method: 'POST',
                url: domain.testUrl + "/Threeinjection/user/queryByUsermobile",
                data: { "mobile": $("#mobile").val() },
                success: function (response) {
                    if (response == "\"no\"") {
                        $("#myModal").find("span").eq(1).text("手机号码已经存在");
                        // $("#mobile").focus();  
                        return;
                    }
                }
            });
        }
    });
    $("#mail").blur(function () {
        $("#myModal").find("span").eq(2).text("");
        if ($("#mail").val().length > 0) {
            var myReg = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/;
            if (!myReg.test($("#mail").val())) {
                $("#myModal").find("span").eq(2).text("邮箱格式输入不正确");
                //  $("#mail").focus();
                return;
            }

        }
    });
    $("#company_name").blur(function () {
        console.log(123);
        $("#myModal").find("span").eq(3).text("");
        if ($("#company_name").val().length == 0) {

            $("#myModal").find("span").eq(3).text("单位名称不能为空");
            //  $("#company_name").focus();
            return;
        } else {
            $("#myModal").find("span").eq(3).text("");

        }

    });
    var table = "userinfo";
    $("#addtj").click(function () {
        var AZ = ["user_name", "account", "user_pwd", "company_id", "sex", "role_id", "enter_state", "email", "mobile"];//字段
        //var valAZ=["user_name","account","user_pwd","company_id","role_id","enter_state","email","mobile"];//字段

        //console.log(findval);
        $("#myModal").find("span").empty();
        //  return;
        //var dataadd={tableName:"userinfo","fieldlist":"user_name','account','user_pwd','company_id','sex','role_id','enter_state','email','mobile'",
        //  "stringvalueA":"'"+$("#user_name").val()+"',"+"'"+$("#user_name").val()+"',"+"'"+hex_md5("123456").toUpperCase()+"',"+"'"+$("#company_id").val()+"',"+"'"+$("#sex").val()+"',"+"'"+$("#jiaose").val()+"',"+"'"+$("#static").val()+"',"+"'"+$("#mail").val()+"',"+"'"+$("#mobile").val()+"'"}
        $("#user_name").blur(); $("#mobile").blur();
        $("#mail").blur(); $("#company_name").blur();


        //{“tableName”:”表名”, “fielded”:”user_id+”，” value”:”修改条件”}

        if ($("#myModalLabel").text() == "新增") {
            //var dataadd={tableName:"userinfo",fieldnameA:"user_name",fieldnameB:"account",fieldnameC:"user_pwd",fieldnameD:"company_id",fieldnameE:"role_id",fieldnameF:"enter_state",fieldnameG:"email",fieldnameH:"mobile",
            // stringvalueA:$("#user_name").val(),stringvalueB:$("#user_name").val(),stringvalueC:hex_md5("123456").toUpperCase(),stringvalueD:$("#company_id").val(),stringvalueE:$("#sex").val(),stringvalueF:$("#jiaose").val(),stringvalueL:$("#static").val(),stringvalueG:$("#mail").val(),stringvalueH:$("#mobile").val()}
            var val = [];//数据
            val.push($("#user_name").val());
            val.push($("#user_name").val());
            val.push(hex_md5("123456").toUpperCase());
            val.push($("#company_id").val());
            val.push($("#sex").val());
            val.push($("#jiaose").val());
            val.push($("#static").val());
            val.push($("#mail").val());
            val.push($("#mobile").val());

            var findval = domain.fieldthis(AZ, val, table);
            //var json=
            // {"tableName":"userinfo", "fielded":""，” valueid”:”修改条件”,”fieldnameA”:”需要修改的字段”，”stringvalueA”:”修改值” }
            setTimeout(function () {
                if ($("#myModal").find("span").text().length > 0) {
                    return;
                }
                $.ajax({
                    type: "POST",
                    url: domain.testUrl + "/Threeinjection/global/insert",
                    // url:domain.testUrl+"/basicmManagementpage/insertCompany",
                    data: findval,
                    success: function (response) {

                        response = JSON.parse(response);
                        if (response.code == "200") {

                            $(".close").click();
                            pageval = 1;

                            cxlist();
                            swal("success!", "保存成功", "success");
                        }

                    }
                });
            }, 600);
        } else {
            var val2 = [];//数据
            val2.push($("#user_name").val());
            val2.push($("#user_name").val());
            val2.push(hex_md5("123456").toUpperCase());
            val2.push($("#company_id").val());
            val2.push($("#sex").val());
            // alert($("#jiaose").val());
            val2.push($("#jiaose").val());
            val2.push($("#static").val());
            val2.push($("#mail").val());
            val2.push($("#mobile").val());
            var findval = domain.fieldupdatethis(AZ, val2, "user_id", $("#user_id").val(), table);
            setTimeout(function () {
                if ($("#myModal").find("span").text().length > 0) {
                    return;
                }
                $.ajax({
                    type: "POST",
                    url: domain.testUrl + "/Threeinjection/global/update",
                    data: findval,
                    success: function (response) {

                        response = JSON.parse(response);
                        if (response.code == "200") {
                            pageval = 1;
                            cxlist();
                            $(".close").click();
                            swal("success!", "修改成功", "success");

                        }

                    }
                });
            }, 600);
        }
    });


    $("#deleUser").click(function () {
        var userids = "";
        var ids = $("#table_list_1").jqGrid("getGridParam", "selarrrow");

        //遍历访问这个集合
        $(ids).each(function (index, id) {
            //由id获得对应数据行
            var row = $("#table_list_1").jqGrid('getRowData', id);
            userids += row.user_id + ","

        });
        userids = userids.substring(0, userids.length - 1);
        // console.log(programid);
        if (re_records == 0 || re_records == null) {
            swal("提示", "暂无用户，请先添加！", "info");
            return;
        } else {
            if (userids == "") {

                swal("OMG!", "请选择需要删除的用户", "error");
                return;
            } else {
                var msg = "确定删除此用户吗？";
                if (confirm(msg) == true) {
                    $.fn.jqLoading({ height: 100, width: 240, text: "正在删除中，请耐心等待...." });
                    $.ajax({
                        type: 'POST',
                        url: domain.testUrl + "/Threeinjection/user/deleteUserInfo",
                        data: { "userId": userids, sessionid: sessionStorage.getItem("sid") },

                        success: function (response) {
                            response = JSON.parse(response);
                            if (response.code == "200") {

                                pageval = 1;
                                cxlist();
                                $.fn.jqLoading("destroy");
                                swal("success!", "删除成功", "success");


                            } else {
                                $.fn.jqLoading("destroy");
                                swal("success!", "删除失败", "success");
                            }

                        }
                    });
                    return true;
                } else {
                    return false;
                }
            }
        }

    });
});
Date.prototype.Format = function (fmt) {
    //author:wangweizhen
    var o = {
        "M+": this.getMonth() + 1,                 //月份   
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时   
        "m+": this.getMinutes(),                 //分   
        "s+": this.getSeconds(),                 //秒   
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度   
        "S": this.getMilliseconds()             //毫秒   
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

window.modify = function (i) {
    $("#myModal").find("span").empty();
    $("#user_name").attr("disabled", "disabled");

    $("#myModalLabel").text("修改");

    $("#update").click();
    i = i - 1;
    var jsonval = JSON.parse(json);

    // $("#user_name").val(json[i].email);

    $("#user_name").val(jsonval.rows[i].user_name);
    mobile = jsonval.rows[i].mobile;
    $("#mobile").val(jsonval.rows[i].mobile);
    $("#mail").val(jsonval.rows[i].email);

    $("#sex").val(jsonval.rows[i].sex);

    $("#company_name").val(jsonval.rows[i].coName);
    //alert(jsonval.rows[i].companyId);
    $("#company_id").val(jsonval.rows[i].companyId);
    $("#user_id").val(jsonval.rows[i].user_id);

    //选中的是管理员
    if (jsonval.rows[i].user_id != "1" && jsonval.rows[i].roleId == "1") {
        $("#jiaose").attr("disabled", "disabled");
    }
    //用户不是管理员
    if (sessionStorage.getItem("userId") != "1" && sessionStorage.getItem("roleId") == "1") {
        $("#jiaose option:first").hide();
        // $("#jiaose").removeAttr("disabled");
    }
    //用户是管理员
    if (sessionStorage.getItem("userId") == "1" && sessionStorage.getItem("roleId") == "1") {
        $("#jiaose").removeAttr("disabled");
    }



    $("#jiaose").val(jsonval.rows[i].roleId);
    $("#static").val(jsonval.rows[i].enter_state);

    if (typeof (jsonval.rows[i].sex) == "undefined") {

        $("#sex").val("1");
    }
    if (typeof (jsonval.rows[i].enter_state) == "undefined") {

        $("#static").val("1");
    }

    //$("#static").val("1");


    // domain.jsonthis.userinfo=[json.rows[i].user_name];

};

